package com.example.hotHub.controller;


import com.example.hotHub.common.R;
import com.example.hotHub.enums.QuoteTypeEnum;
import com.example.hotHub.model.Quote;
import com.example.hotHub.utils.RestTemplateUtil;
import com.example.hotHub.utils.SimpleMap;
import io.swagger.annotations.Api;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin
@Api(tags = "一言爬取控制器")
@RestController
public class QuoteController {

    @GetMapping("/quote")
    public R getQuote() {
        RestTemplateUtil restTemplateUtil = new RestTemplateUtil();
        String url = "https://v1.hitokoto.cn/?encode=json&c=" + QuoteTypeEnum.getRandomQuoteType().getTypeCode();
        SimpleMap response = restTemplateUtil.doGet(url, null, null, SimpleMap.class);

        String content = response.getString("hitokoto");
        String from = response.getString("from");
        String from_who = response.getString("from_who");

        String author = null;
        if (StringUtils.hasLength(from_who)) {
            author = from + "(" + from_who + ")";
        } else {
            author = from;
        }

        Quote quote = new Quote(content, author);
        return R.success(quote);
    }

}
